package com.qianqian.service.service.wxcpapi;

import com.alibaba.fastjson.JSONObject;
import com.qianqian.service.config.WxCpHttpClientConfig;
import com.qianqian.service.utils.WxcpTokenCacheTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public abstract class WxCpRequestService  extends WxCpHttpClientConfig {
    private static final Logger log = LoggerFactory.getLogger(WxCpRequestService.class);

    public void refreshAccessToken(){
        HashMap<String,String> map = new HashMap<>();
        map.put("corpid",getCorpId());
        map.put("corpsecret",getCorpSecret());
        JSONObject token = super.get("gettoken",map);
        WxcpTokenCacheTools wxcpTokenCacheTools = WxcpTokenCacheTools.getWxcpTokenCache();
        wxcpTokenCacheTools.setAccessToken(getCorpSecret(),token.getString("access_token"));
        wxcpTokenCacheTools.setExpiresIn(getCorpSecret(),token.getInteger("expires_in"));
        wxcpTokenCacheTools.setExpiresTime(getCorpSecret(),System.currentTimeMillis() + (wxcpTokenCacheTools.getExpiresIn(getCorpSecret()) - 200) * 1000L);
    }

    public boolean isAccessTokenExpired() {
        WxcpTokenCacheTools wxcpTokenCacheTools = WxcpTokenCacheTools.getWxcpTokenCache();
        if(wxcpTokenCacheTools.getAccessToken(getCorpSecret())==null){
            return true;
        }
        return System.currentTimeMillis() > wxcpTokenCacheTools.getExpiresTime(getCorpSecret());
    }
    public JSONObject get(String path, Map<String, String> paramMap){
        if(isAccessTokenExpired()){
            refreshAccessToken();
        }
        return super.get(path,paramMap,WxcpTokenCacheTools.getWxcpTokenCache().getAccessToken(getCorpSecret()));
    }
    public JSONObject post(String path, Map<String, String> param,String data){
        if(isAccessTokenExpired()){
            refreshAccessToken();
        }
        return super.post(path,param,data,WxcpTokenCacheTools.getWxcpTokenCache().getAccessToken(getCorpSecret()));
    }

    public JSONObject post(String path, String data) {
        if(isAccessTokenExpired()){
            refreshAccessToken();
        }
        return super.post(path,data,WxcpTokenCacheTools.getWxcpTokenCache().getAccessToken(getCorpSecret()));
    }
    public abstract String getCorpSecret();
    public abstract Integer getAgentId();
    public abstract String getCorpId();
}
